<?php
use think\Response;
use app\common\lib\ChinesePinyin;

    function create_salt($length=12) {
          return $salt = substr(uniqid(rand()),0,$length);
    }
    function create_md5($string,$salt)
    {
        return md5($string.$salt);
    }
    function uuid() {
        $charid = strtolower(md5(uniqid(rand(), true)));
        return substr($charid,0,24);
    }
    function unid() {
        $charid = strtolower(md5(uniqid(rand(), true)));
        return $charid;
    }
    function jsonError($message = '',$url=null) {
        $return['msg'] = $message;
        $return['code'] = -1;
        $return['url'] = $url;
        $res = json_encode($return,true);
        return Response::create($res)->contentType('text/json');;
        
    }
    function jsonSuccess($message = '',$data = '',$url=null) {
        $return['msg']  = $message;
        $return['data'] = $data;
        $return['code'] = 1;
        $return['url'] = $url;
        $res = json_encode($return,true);
        return Response::create($res)->contentType('text/json');;
    }
    
    function arrayError ($message = '', $data = '', $url = '') {
        $return['msg'] = $message;
        $return['code'] = -1;
        $return['url'] = $url;
        return $return;
    }
    function arraySuccess ($message = '', $data = '', $url = '') {
        $return['msg']  = $message;
        $return['data'] = $data;
        $return['code'] = 1;
        $return['url'] = $url;
        return $return;
    }
    
    function fetch_dir($dir, $file_type = null) {
        $base_dir = realpath($dir);
        if (!file_exists($base_dir)) {
            return false;
        }
        $dir_handle = opendir($base_dir);
        $files_list = array();
        while (($file = readdir($dir_handle)) !== false) {
            if (substr($file, 0, 1) != '.' AND is_dir($base_dir . DS . $file)) {
                $files_list[] = $base_dir . DS . $file;
            }
        }
        closedir($dir_handle);
        return $files_list;
    }
    
    function fetch_file_lists($dir, $file_type = null) {
       if ($file_type) {
    	    if (substr($file_type, 0, 1) == '.') {
                $file_type = substr($file_type, 1);
            }
        }
    
        $base_dir = realpath($dir);
    
        if (!file_exists($base_dir)) {
            return false;
        }
    
        $dir_handle = opendir($base_dir);
    
        $files_list = array();
    
        while (($file = readdir($dir_handle)) !== false) {
            if (substr($file, 0, 1) != '.' AND !is_dir($base_dir . DS . $file)) {
                if (($file_type AND end(explode('.', $file)) == $file_type) OR !$file_type) {
                    $files_list[] = $base_dir . DS . $file;
                }
            }
            else if (substr($file, 0, 1) != '.' AND is_dir($base_dir . DS . $file)) {
                if ($sub_dir_lists = fetch_file_lists($base_dir . DS . $file, $file_type)) {
                    $files_list = array_merge($files_list, $sub_dir_lists);
                }
            }
        }
        closedir($dir_handle);
        return $files_list;
    }
    
    function msectime() {
        list($msec, $sec) = explode(' ', microtime());
        $msectime = (float)sprintf('%.0f' , (floatval($msec) + floatval($sec)) * 1000);
        return $msectime;
    }
    function formatTime($value) {
        if(time() - $value < 60) {
            return (time() - $value).'秒前';
        }
        if(time() - $value > 60 && time() - $value < 3600) {
            return (int)((time() - $value)/60).'分钟前';
        }
        if(time() - $value > 3600 && time() - $value < 86400) {
            return (int)((time() - $value)/3600).'小时前';
        }
        if(time() - $value > 86400 && time() - $value < 172800) {
            return '1天前';
        }
        return date('m-d', $value);
    }
    
    function pushData($api,$urls) {
        $ch = curl_init();
        $options =  array(
            CURLOPT_URL => $api,
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => implode("\n", $urls),
            CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
        );
        curl_setopt_array($ch, $options);
        $result = curl_exec($ch);
        curl_close($ch);
        if ($result) {
            return $result;
        } else {
            return false;
        }
    }
    function getData($api,$postData = '') {
        if (!$api) {
            return false;
        }
        if (empty($postData)) {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $api);
            curl_setopt($ch, CURLOPT_HEADER, 0);
			 curl_setopt($ch, CURLOPT_TIMEOUT, 20); 
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            $result = curl_exec($ch);
    
            curl_close($ch);
        } else {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $api);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_TIMEOUT, 20); 
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            $result = curl_exec($ch);
            curl_close($ch);
        }
        if ($result) {
            return $result;
        } else {
            return null;
        }
    }
    
    function curlData($url) {
        $header = array (
        //  "Host:www.baidu.com",
            "Content-Type:application/x-www-form-urlencoded",//post请求
            "Connection: keep-alive",
            'Referer:http://www.baidu.com',
            'User-Agent: Mozilla/5.0 (compatible; Baiduspider-render/2.0; +http://www.baidu.com/search/spider.html)'
        );
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $html = curl_exec($ch);
        curl_close($ch);
        return $html;
    }
    
    function linkClient($url,$postData = '',$header = '') {
        if (!$url) {
            return false;
        }
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        if ($header) {
            curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
        }
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $html = curl_exec($ch);
        curl_close($ch);
        return $html;
    }
     
    function deleteHtml($str) { 
        $str = preg_replace("/(\s|\r|\n|\t|\&nbsp\;|　| |   |\xc2\xa0)/","",trim(strip_tags($str)));
        return $str; //返回字符串
    }
    
    function getPage($page = 1,$totalNum = 1,$url = '',$endUrl = '.html',$long = 8)
    {
        $oldUrl = $url;
        $url = str_replace('.html','',$url);
        $startUrl = $url . '_';
        $endUrl = $endUrl;
        $long = $long ? $long : 8;
        
        if ($totalNum == 1) {
            $upPage = '<li class="page-item disabled"><span class="page-link">上一页</span></li>';
            $html .= '<li class="page-item disabled"><span class="page-link">1</span></li>';
            $downPage = '<li class="page-item disabled"><span class="page-link">下一页</span></li>';
        } else {
            if ($page == 2) {
                $upPage = '<li class="page-item"><a class="page-link" href="'. $oldUrl . '">上一页</a></li>';
            } else {
                if ($page == 1) {
                    $upPage = '<li class="page-item disabled"><span class="page-link">上一页</span></li>';
                } else {
                    $upPage = '<li class="page-item"><a class="page-link" href="'.$startUrl. ($page - 1) . $endUrl . '">上一页</a></li>';
                }
            }
            for ($i = 1; $i <= intval($totalNum); $i++) {
                    if ($long == 1) {
                        if ($page == $i) {
                            if ($i == 1) {
                                if ($page == $i) {
                                     $html .= '<li class="page-item active"><a class="page-link" href="'. $oldUrl . '">'.$i.'</a></li>';
                                } else {
                                   $html .= '<li class="page-item"><a class="page-link" href="'. $oldUrl . '">'.$i.'</a></li>';
                                }
                            } else {
                                $html .= '<li class="page-item active"><a class="page-link" href="'.$startUrl. $i . $endUrl . '">'.$i.'</a></li>';
                            }
                        }
                    } else {
                        if ($totalNum > 10) {
                            if ($page <= ceil($long / 2) && $i <= $long) {
                                if ($i == 1) {
                                    if ($page == $i) {
                                        $html .= '<li class="page-item active"><a class="page-link" href="'. $oldUrl . '">'.$i.'</a></li>';
                                    } else {
                                        $html .= '<li class="page-item"><a class="page-link" href="'. $oldUrl . '">'.$i.'</a></li>';
                                    }
                                } else {
                                    if ($page == $i) {
                                        $html .= '<li class="page-item active"><a class="page-link" href="'.$startUrl. $i . $endUrl . '">'.$i.'</a></li>';
                                    } else {
                                        $html .= '<li class="page-item"><a class="page-link" href="'.$startUrl. $i . $endUrl . '">'.$i.'</a></li>';
                                    }
                                }
                            } else {
                                if ($page + ceil($long / 2) > $totalNum && $i > $totalNum - $long) {
                                    if ($page == $i) {
                                        $html .= '<li class="page-item active"><a class="page-link" href="'.$startUrl. $i . $endUrl . '">'.$i.'</a></li>';
                                    } else {
                                        $html .= '<li class="page-item"><a class="page-link" href="'.$startUrl. $i . $endUrl . '">'.$i.'</a></li>';
                                    }
                                } else {
                                    if ($page - ceil($long / 2) <= $i  && $i <= $page + ceil($long / 2)) {
                                        if ($i == 1) {
                                            if ($page == $i) {
                                                $html .= '<li class="page-item active"><a class="page-link" href="'. $oldUrl . '">'.$i.'</a></li>';
                                            } else {
                                                $html .= '<li class="page-item"><a class="page-link" href="'. $oldUrl . '">'.$i.'</a></li>';
                                            }
                                        } else {
                                            if ($page == $i) {
                                                $html .= '<li class="page-item active"><a class="page-link" href="'.$startUrl. $i . $endUrl . '">'.$i.'</a></li>';
                                            } else {
                                                $html .= '<li class="page-item"><a class="page-link" href="'.$startUrl. $i . $endUrl . '">'.$i.'</a></li>';
                                            }
                                        }
                                    }
                                }
                            }
                        } else {
                            if ($i == 1) {
                                if ($page == $i) {
                                     $html .= '<li class="page-item active"><a class="page-link" href="'. $oldUrl . '">'.$i.'</a></li>';
                                } else {
                                   $html .= '<li class="page-item"><a class="page-link" href="'. $oldUrl . '">'.$i.'</a></li>';
                                }
                            } else {
                                if ($page == $i) {
                                    $html .= '<li class="page-item active"><a class="page-link" href="'.$startUrl. $i . $endUrl . '">'.$i.'</a></li>';
                                } else {
                                    $html .= '<li class="page-item"><a class="page-link" href="'.$startUrl. $i . $endUrl . '">'.$i.'</a></li>';
                                }
                            }
                        }
                    }
            }
            if ($page == $totalNum) {
                $downPage = '<li class="page-item disabled"><span class="page-link">下一页</span></li>';
            } else {
                $downPage = '<li class="page-item"><a class="page-link" href="'.$startUrl. ($page + 1) . $endUrl . '">下一页</a></li>';
            }
        }
        $html = '<ul class="pagination"><li class="page-item disabled"><span class="page-link">共'.$totalNum.'页</span></li> ' . $upPage . $html . $downPage . '</ul>';
        return $html;
    }

    
    function format_url($srcurl, $baseurl) {  
        $srcinfo = parse_url($srcurl);  
        if(isset($srcinfo['scheme'])) {  
            return $srcurl;  
        }  
        $baseinfo = parse_url($baseurl);  
        $url = $baseinfo['scheme'].'://'.$baseinfo['host'];  
      
        if (substr($srcinfo['path'], 0, 1) == '/') {  
            $path = $srcinfo['path'];  
        } else {  
            $path = $baseinfo['path'].'/'.$srcinfo['path'];  
        }  
        $rst = array();  
        $path_array = explode('/', $path);  
        if(!$path_array[0]) {  
            $rst[] = '';  
        }  
        foreach ($path_array AS $key => $dir) {  
            if ($dir == '..') {  
                if (end($rst) == '..') {  
                    $rst[] = '..';  
                } elseif(!array_pop($rst)) {  
                    $rst[] = '..';  
                }  
            } elseif($dir && $dir != '.') {  
                $rst[] = $dir;  
            }  
        }  
        if(!end($path_array)) {  
            $rst[] = '';  
        }  
        $url .= implode('/', $rst);  
        return str_replace('\\', '/', $url);  
    }  
 
    function gbkToUTF8($html) {
        $arr = array( "UTF-8", "ASCII", "GBK", "GB2312", "gb2312","BIG5", "JIS", "eucjp-win", "sjis-win", "EUC-JP" );
        $encode  = mb_detect_encoding( $html, $arr );    
        $encode = $encode ? $encode : 'gb2312';
        $html = mb_convert_encoding(trim($html), "UTF-8", $encode);
        $html = str_replace('charset=GB2312','charset=UTF-8',$html);
        $html = str_replace('charset="GB2312"','charset="UTF-8"',$html);
        $html = str_replace("charset='GB2312'","charset='UTF-8'",$html);
        $html = str_replace('charset=gb2312','charset=UTF-8',$html);
        $html = str_replace('charset="gb2312"','charset="UTF-8"',$html);
        $html = str_replace("charset='gb2312'","charset='UTF-8'",$html);
        $html = str_replace('charset=GBK','charset=UTF-8',$html);
        $html = str_replace('charset="GBK"','charset="UTF-8"',$html);
        $html = str_replace("charset='GBK'","charset='UTF-8'",$html);
        $html = str_replace('charset=gbk','charset=UTF-8',$html);
        $html = str_replace('charset="gbk"','charset="UTF-8"',$html);
        $html = str_replace("charset='gbk'","charset='UTF-8'",$html);
        return $html;
    }
        
    function getImage($url,$save_dir,$filename = '',$type = 0) {
        if (!$url) {
             return false;
        }
        if (!$save_dir) {
             return false;
        }
        $ext = strrchr($url,'.');
        if ($ext != '.gif' && $ext != '.jpg' &&  $ext != '.png' && $ext != '.jpeg') {
            $ext = '.jpg';
        }
        $filename = uuid() . $ext;
        if (0 !== strrpos($save_dir, DS )){
            $save_dir.= DS;
        }
        if (!file_exists($save_dir)&&!mkdir($save_dir,0777,true)) {
            return array('file_name'=>'','save_path'=>'','error'=>5);
        }
        if ($type) {  
            $ch = curl_init();  
            $timeout = 30;
            curl_setopt($ch, CURLOPT_URL, $url);  
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            curl_setopt($ch, CURLOPT_ENCODING,'gzip');
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);  
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            $content = curl_exec($ch);  
            curl_close($ch);  
        } else {  
            ob_start();  
            readfile($url);  
            $content = ob_get_contents();  
            ob_end_clean();
        }  
       
        $fp2 = @fopen($save_dir . $filename, 'a');  
        fwrite($fp2, $content);  
        fclose($fp2);  
        unset($content, $url);  
         
        return array('file_name'=>$filename,'save_path'=>$save_dir.$filename,'error'=>0);
    }
    if (is_file(APP_PATH . DS . 'function.php')) {
        require APP_PATH . DS . 'function.php';
    }
    if (is_dir(ROOT_PATH . 'addons' . DS)) {
        foreach (fetch_dir(ROOT_PATH . 'addons' . DS) as $key => $dir) {
            if (is_file($dir . DS . 'function.php')) {
                require $dir . DS . 'function.php';
            }
        }
    }
    function getPinyin($name) {
        if (!$name) {
           return false;
        }
        if (preg_match('/^[a-zA-Z0-9]+$/',$name)) {
            return $name;
        }
        if (preg_match('/^[\x7f-\xff]+$/', $name)) {
            $Pinyin = new ChinesePinyin();
            $result = $Pinyin->TransformWithoutTone($name);
            return $result;
        }
        return '';
    }
 
	function getImagetype($filename) {
        $file = fopen($filename, 'rb');
        $bin = fread($file, 2);
        fclose($file);
        $strInfo = @unpack('C2chars', $bin);
        $typeCode = intval($strInfo['chars1'] . $strInfo['chars2']);
        $fileType = '';
        switch ($typeCode) {
            case 255216:
                $fileType = 'jpg';
            break;
            case 7173:
                $fileType = 'gif';
            break;
            case 6677:
                $fileType = 'bmp';
            break;
            case 13780:
                $fileType = 'png';
            break;
            default:
                $fileType = '只能上传图片类型格式';
        }
        return $fileType;
	}
	
	function transByte($byte)
	{
	    $KB = 1024;
	    $MB = 1024 * $KB;
	    $GB = 1024 * $MB;
	    $TB = 1024 * $GB;
	    if ($byte < $KB) {
	        return $byte . "B";
	    } elseif ($byte < $MB) {
	        return round($byte / $KB, 2) . "KB";
	    } elseif ($byte < $GB) {
	        return round($byte / $MB, 2) . "MB";
	    } elseif ($byte < $TB) {
	        return round($byte / $GB, 2) . "GB";
	    } else {
	        return round($byte / $TB, 2) . "TB";
	    }
	}
	
	function getRandomString($len, $chars = null)
	{
	    if (is_null($chars)) {
	        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	    } 
	    mt_srand(10000000*(double)microtime());
	    for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < $len; $i++) {
	        $str .= $chars[mt_rand(0, $lc)]; 
	    }
	    return $str;
	}
	
	function toHex($N) {
	    if ($N==NULL) return "00";
	    if ($N==0) return "00";
	    $N=max(0,$N); 
	    $N=min($N,255); 
	    $N=round($N);
	    $string = "0123456789ABCDEF";
	    $val = (($N-$N%16)/16);
	    $s1 = $string{$val};
	    $val = ($N%16);
	    $s2 = $string{$val};
	    return $s1.$s2;
	}
	//颜色值转换为16进制数字
	function rgb2hex($r,$g,$b){
	    return toHex($r).toHex($g).toHex($b);
	}
	//16进制数字转换为颜色值
	function hex2rgb($N){
	    $dou = str_split($N,2);
	    return array(
	        "R" => hexdec($dou[0]), 
	        "G" => hexdec($dou[1]), 
	        "B" => hexdec($dou[2])
	    );
	}
	
	function autolink($str, $attributes = array()) {
	    $attrs = '';
	    foreach ($attributes as $attribute => $value) {
	        $attrs .= " {$attribute}=\"{$value}\"";
	    }
	    $str = ' '.$str;
	    $str = preg_replace('`([^"=\'>])((http|https|ftp|ftps)://[^\s< ]+[^\s<\.)])`i', '$1<a href="$2" rel="external nofollow" target="_blank" '.$attrs.'>网页链接</a>', $str);
	    $str = substr($str, 1);
	    return $str;
	}